﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MDF.Utilites.Helper
{

    public class HtmlHelper
    {
        /// <summary>
        /// Get all data of form
        /// </summary>
        /// <param name="html">html content</param>
        /// <param name="xpathForm">the xpath to find form</param>
        /// <returns>List of form</returns>
        public static List<KeyValuePair<string, string>> GetFormData(string html, string xpathForm)
        {
            List<KeyValuePair<string, string>> lstDatas = new List<KeyValuePair<string, string>>();

            #region 1.Verify input

            if (string.IsNullOrEmpty(html))
                throw new Exception("The html input is not empty");
            if (string.IsNullOrEmpty(xpathForm))
                throw new Exception("The xpathForm input is not empty");

            #endregion

            #region 2.Get from data
            //Load html
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var formNode = doc.DocumentNode.SelectNodes(xpathForm);

            #region 2.1Verify form

            if (formNode == null || formNode.Count == 0)
                throw new Exception("Can not find the form");
            if (formNode.Count != 1)
            {
                throw new Exception("More than 1 the form");
            }

            #endregion

            //Load form
            HtmlAgilityPack.HtmlDocument docNames = new HtmlAgilityPack.HtmlDocument();
            docNames.LoadHtml(formNode[0].ParentNode.InnerHtml);

            //Get all tag have name atrribute
            var names = docNames.DocumentNode.SelectNodes("//*[@name]");
            if (names == null || names.Count == 0)
                return lstDatas;
            foreach (var item in names)
            {

                string strKey = "";
                string strValue = "";
                try
                {
                    if (item.Attributes["name"] != null)
                        strKey = item.Attributes["name"].Value;
                    if (item.Attributes["value"] != null)
                        strValue = item.Attributes["value"].Value;
                    if (string.IsNullOrEmpty(strValue))
                    {
                        HtmlAgilityPack.HtmlDocument selectes = new HtmlAgilityPack.HtmlDocument();
                        selectes.LoadHtml(item.OuterHtml);
                        if (selectes != null)
                        {
                            var nodes = selectes.DocumentNode.SelectNodes("//*[@selected]");
                            if (nodes == null)
                                nodes = selectes.DocumentNode.SelectNodes("//*[@checked]");
                            if (nodes != null && nodes[0].Attributes["value"] != null)
                                strValue = nodes[0].Attributes["value"].Value;
                        }
                    }
                    KeyValuePair<string, string> dataTemp = new KeyValuePair<string, string>(strKey, strValue);
                    lstDatas.Add(dataTemp);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
            return lstDatas;
        }
        /// <summary>
        /// Create string of data to post
        /// </summary>
        /// <param name="lstData">List data</param>
        /// <returns>String post</returns>
        public static string GenFormData(List<KeyValuePair<string, string>> lstData)
        {
            if (lstData == null)
                throw new Exception("lstData is null");
            string strData = "";
            foreach (var item in lstData)
            {
                strData += string.Format("{0}={1}&", HttpUtility.UrlEncode(item.Key), HttpUtility.UrlEncode(item.Value));
            }
            if (strData.Length > 0)
            {
                strData = strData.Substring(0, strData.Length - 1);
            }
            return strData;
        }

        public static List<KeyValuePair<string, string>> UpdateFormData(List<KeyValuePair<string, string>> lstData, string key, string value)
        {
            var query = lstData.Where(m => m.Key.IndexOf(key) > -1);
            if (query != null && query.Count() > 0 && lstData.Count > 0)
            {
                for (int i = 0; i < lstData.Count; i++)
                {
                    if (lstData[i].Key.IndexOf(key) > -1)
                    {
                        lstData[i] = new KeyValuePair<string, string>(lstData[i].Key, value);
                    }
                }
            }
            else
            {
                var newItem = new KeyValuePair<string, string>(key, value);
                lstData.Add(newItem);
            }

            return lstData;
        }

        public static List<KeyValuePair<string, string>> DeleteFormData(List<KeyValuePair<string, string>> lstData, string key)
        {
            var query = lstData.Where(m => m.Key.IndexOf(key) > -1);
            if (query != null && lstData.Count > 0)
            {
                for (int i = 0; i < lstData.Count; i++)
                {
                    if (lstData[i].Key.IndexOf(key) > -1)
                    {
                        lstData.RemoveAt(i);
                    }
                }
            }
            return lstData;
        }
    }
}
